/**
* @project admin-go-api
* @name sysLoginInfo
* @descriptions 登录日志数据层
* @author 寒锋
* @date 2023-12-22 14:10:53
 */

package dao

import (
	"admin-go-api/api/entity"
	"admin-go-api/common/util"
	. "admin-go-api/pkg/db"
	"time"
)

// CreateSysLoginInfo 添加登录日志
func CreateSysLoginInfo(username, ipAddress, loginLocation, browser, os, message string, loginStatus int) bool {
	sysLoginInfo := entity.SysLoginInfo{
		Username:      username,
		IpAddress:     ipAddress,
		LoginLocation: loginLocation,
		Browser:       browser,
		Os:            os,
		Message:       message,
		LoginStatus:   loginStatus,
		LoginTime:     util.HTime{Time: time.Now()},
	}
	result := Db.Create(&sysLoginInfo)
	if result.RowsAffected > 0 {
		return true
	}
	return false
}

// GetSysLoginInfoList 获取登录日志列表
func GetSysLoginInfoList(PageNum, PageSize, LoginStatus int, Username, BeginTime, EndTime string) (sysLoginInfo []entity.SysLoginInfo, count int64) {
	model := Db.Table("sys_login_info")
	if Username != "" {
		model = model.Where("username = ?", Username)
	}
	if LoginStatus != 0 {
		model = model.Where("login_status =?", LoginStatus)
	}
	if BeginTime != "" && EndTime != "" {
		model = model.Where("login_time between ? and ?", BeginTime, EndTime)
	}
	model.Count(&count)
	model.Limit(PageSize).Offset((PageNum - 1) * PageSize).Order("login_time desc").Find(&sysLoginInfo)
	return sysLoginInfo, count
}

// DeleteSysLoginInfoById 根据id删除日志
func DeleteSysLoginInfoById(dto entity.SysLoginInfoIdDto) bool {
	result := Db.Delete(&entity.SysLoginInfo{}, dto.Id)
	if result.RowsAffected > 0 {
		return true
	}
	return false
}

// BatchDeleteSysLoginInfo 批量删除日志
func BatchDeleteSysLoginInfo(dto entity.DelSysLoginInfoDto) bool {
	result := Db.Where("id in (?)", dto.Ids).Delete(&entity.SysLoginInfo{})
	if result.RowsAffected > 0 {
		return true
	}
	return false
}

// CleanSysLoginInfo 清空日志
func CleanSysLoginInfo() bool {
	result := Db.Exec("truncate table sys_login_Info")
	if result.Error == nil {
		return true
	}
	return false
}
